package webapp.mvc.oss.impl;

import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.GetPolicy;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.URLUtils;
import com.zoowii.jpa_utils.util.StringUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import webapp.mvc.oss.IStoreService;
import webapp.mvc.oss.ObjectStoreInfo;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;

public class QiniuStoreService implements IStoreService {
    private static final Logger LOG = LoggerFactory.getLogger(QiniuStoreService.class);

    private static final String QINIU_BUCKET_HOST = "7xja1y.com1.z0.glb.clouddn.com";

    static {
        Config.ACCESS_KEY = "EHaauCujLT-H8OCjwGkxAiMlChA09FffXCSv_0ll";
        Config.SECRET_KEY = "4TAGGCN427stf1X9rM2zBTWy-xyn2u_M13xiyyAx";
    }

    private static final String BUCKET_NAME = "jxlhfiles";

    @Override
    public ObjectStoreInfo putFile(InputStream inputStream, String fileName) throws IOException {
        String fileKey = StringUtil.randomString(20) + "_" + fileName;
        fileKey = fileKey.replaceAll("\\.", "_");
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        PutPolicy putPolicy = new PutPolicy(BUCKET_NAME);
        try {
            String upToken = putPolicy.token(mac);
            PutExtra putExtra = new PutExtra();
            PutRet putRet = IoApi.Put(upToken, fileKey, inputStream, putExtra);
            ObjectStoreInfo objectStoreInfo = new ObjectStoreInfo();
            objectStoreInfo.setHash(putRet.getHash());
            objectStoreInfo.setKey(putRet.getKey());
            objectStoreInfo.setService("qiniu");
            return objectStoreInfo;
        } catch(Exception e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

    @Override
    public String getFile(HttpServletRequest request, String storeKey, String id) throws IOException {
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        try {
            String baseUrl = URLUtils.makeBaseUrl(QINIU_BUCKET_HOST, storeKey) + "?imageView2/1/w/400/h/400/q/75";
            GetPolicy getPolicy = new GetPolicy();
            return getPolicy.makeRequest(baseUrl, mac);
        }catch (Exception e) {
            throw new IOException(e);
        }
    }

    @Override
    public InputStream getFileStream(String storeKey) throws IOException {
        throw new IOException("not supported");
    }

    @Override
    public boolean supportFetchFileDataDirect() {
        return false;
    }
}
